class Bible
  class << self
    def is_letter?(char)
      if char.is_a?(String)
      asc = char[0].to_i
      else
      asc = char.to_i
      end
      return 48 <= asc && asc <=57 || 65 <= asc && asc <= 90 || 97 <= asc && asc <= 122
    end

    def write_index_file(filename, linenumber, val)
      filepath = File.dirname(filename)
      if !File.exists?(filepath)
      Dir.mkdir(filepath)
      end
      if linenumber == 1
      f = File.new(filename, 'wb')
      else
      f = File.new(filename, 'ab')
      end
      content = "Line %d: %s %s" % [linenumber, val.join(', '), "\n"]
      f.write(content)
      f.close
    end

    def process_line(linenumber, line)
      puts "processing line %d" % linenumber
      words_hash = split_word(line)
      words_hash.each do |key, val|
        filename = File.join(File.dirname(File.expand_path(__FILE__)), 'index', key+'.txt')
        write_index_file(filename, linenumber, val)
      end
    end

    def split_word(line)
      str_len = line.length
      words_hash = {}
      word_start, word_start_pos, word_end_pos = false, 0, 0

      for i in 0...str_len
        # for a word's beginning
        if is_letter?(line[i]) && !word_start
        word_start, word_start_pos = true, i
        end

        # for a word's ending
        if !is_letter?(line[i]) && word_start
        word_start, word_end_pos = false, i
        word = line[word_start_pos...word_end_pos]
        (words_hash[word.downcase] ||= []) << word_start_pos
        end
      end

      return words_hash
    end
  end
end